package com.example.movie_shop.controller;


import cn.hutool.core.util.IdUtil;
import com.example.movie_shop.entry.User;
import com.example.movie_shop.service.UserService;
import com.example.movie_shop.xunfei.face.WebFaceCompare;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
//import javax.xml.ws.Service;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;


@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Value("${file.upload-path}")
    private String upload_path;

    //用户注册
    @RequestMapping("user_reg")
    public boolean regist(User user){
        return userService.save(user);
    }

    //用户登录
    @RequestMapping("/user_login")
    public User login(User user){
        return userService.login(user);
    }

    //用户头像上传与更改
    @RequestMapping("/upload_user")
    public User upload(@RequestParam("my_file") MultipartFile multipartFile, User user, ServletRequest request){
        String fileUrl = "";
        String newName = null;
        //获取原文件名，若文件需要下载，则把原文件名保存到数据库
        String oldName = multipartFile.getOriginalFilename();

        if(!"".equals(oldName) && oldName!=null){
            int year = LocalDate.now().getYear();
            int month = LocalDate.now().getMonthValue();
            //创建上传目录
            String tarDir = year + "_" +month;
            File up_dir = new File(upload_path+tarDir);
            if(!up_dir.exists()){
                up_dir.mkdir();
            }
            //获取文件格式,后缀
            String suffix = oldName.substring(oldName.lastIndexOf("."));
            newName = IdUtil.simpleUUID()+suffix;
            //创建新文件夹
            File fileNew = new File(up_dir,newName);

            //获取文件访问路径，注意此时需要由配置类，进行访问路径映射（FilePathConfig）
            try{
                //文件上传
                multipartFile.transferTo(fileNew);

                //获取ip或域名
                String serverName = request.getServerName();

                //获取端口
                int serverPort = request.getServerPort();

                //拼接成外部可以访问的地址 ”/upload/“ 为路径映射配置的名称
                fileUrl = "http://"+serverName+":"+serverPort+"/upload/"+tarDir+"/"+newName;
//                System.out.println("文件路径"+fileUrl);


            } catch (IOException e){
                e.printStackTrace();
            }
            //保存用户头像
//            user.setIcon(newName);
            user.setIcon(fileUrl);
        }

        //更新用户信息
        userService.updateById(user);
        User newUser = userService.getById(user.getId());
        return newUser;
    }

    //人脸识别
    @RequestMapping("/up_photo")
    public boolean regist_photo(@RequestParam("user_pic") MultipartFile user_pic, User user, ServletRequest request){
        String tarDir = "faces";

        //获取原文件名，若文件需要下载，则把原文件名保存到数据库
        String oldName = user_pic.getOriginalFilename();
        //创建上传目录
        File up_dir = new File(upload_path+tarDir);
        if(!up_dir.exists()){
            up_dir.mkdir();
        }
        //获取文件格式,后缀
        String suffix = oldName.substring(oldName.lastIndexOf("."));
        String newName = IdUtil.simpleUUID()+suffix;
        //创建新文件夹
        File fileNew = new File(up_dir,newName);
        //文件上传
        try {
            user_pic.transferTo(fileNew);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //把上传的证件照添加到用户信息中
        user.setFace(newName); //"photos/"+
        userService.updateById(user);
        return false;
    }

    //人脸登录
    @RequestMapping("/face_login")
    public User face_login(@RequestParam("face_photo") MultipartFile face_photo){
        String tarDir = "temp";

        //获取原文件名，若文件需要下载，则把原文件名保存到数据库
        String oldName = face_photo.getOriginalFilename();
        //创建上传目录
        File up_dir = new File(upload_path+tarDir);
        if(!up_dir.exists()){
            up_dir.mkdir();
        }
        //获取文件格式,后缀
        String suffix = oldName.substring(oldName.lastIndexOf("."));
        String newName = IdUtil.simpleUUID()+suffix;
        //创建新文件夹
        File fileNew = new File(up_dir,newName);
        //文件上传
        try {
            face_photo.transferTo(fileNew);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String tp = upload_path+"temp/"+newName;
        //现在获得了用户的一张照片和一张证件照，要进行人脸相似度对比（算法）
        File faceDir = new File(upload_path+"faces");
        File facesFile[] = faceDir.listFiles(); //将人脸库文件保存为list
        // 遍历人脸库进行对比
        int ct = 1;
        double max_score=0;
        String tar_face_name = "";
        for (File face:facesFile){
            String fp = upload_path+"faces/"+face.getName();
            Double r =WebFaceCompare.compire(fp,tp);
            if(max_score<r){
                max_score = r;
                tar_face_name = face.getName(); //"faces/"+
            }
            System.out.println("第"+ct+"次比对得分为："+r);
            ct++;
        }
        User user = new User();
        if (max_score>0.85){
            user = userService.getByFace(tar_face_name);
        }
        return user;
    }

}
